package com.mmall.service.impl;

import com.google.common.collect.Sets;
import com.mmall.common.ServerResponse;
import com.mmall.dao.CategoryMapper;
import com.mmall.pojo.Category;
import com.mmall.service.ICategoryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;


/**
 * Created by Administrator on 2017/6/5 0005.
 */
@Service("iCategoryService")
public class CategoryServiceImpl implements ICategoryService {

    //添加日志对象
    private Logger logger = LoggerFactory.getLogger(CategoryServiceImpl.class);


    @Autowired
    private CategoryMapper categoryMapper;

    public ServerResponse addCategory(String categoryName, Integer parentId) {

        if (parentId == null || StringUtils.isEmpty(parentId)) {
            return ServerResponse.createByErrorMessage("添加品类参数错误");
        }

        Category category = new Category();
        category.setName(categoryName);
        category.setParentId(parentId);
        category.setStatus(true);

        int rowCount = categoryMapper.insert(category);
        if (rowCount > 0) {
            return ServerResponse.createBySuccessMessage("添加品成功");
        } else {
            return ServerResponse.createByErrorMessage("添加品失败");
        }
    }


    public ServerResponse updateCategoryName(int categoryId, String categoryName) {
        if (categoryName == null || StringUtils.isEmpty(categoryId)) {
            return ServerResponse.createByErrorMessage("更新品类名称参数错误");
        }
        Category category = new Category();
        category.setParentId(categoryId);
        category.setName(categoryName);
        int rowCount = categoryMapper.updateByPrimaryKeySelective(category);

        if (rowCount > 0) {
            return ServerResponse.createBySuccessMessage("更新品类成功");
        } else {
            return ServerResponse.createByErrorMessage("更新品类失败");
        }
    }


    public ServerResponse<List<Category>> getChildrenParallelCategory(Integer categoryId) {

        List<Category> categoryList = categoryMapper.selectCategoryChildrenByParentId(categoryId);

        if (CollectionUtils.isEmpty(categoryList)) {
            logger.info("未找到当前分类的子分类");
        }
        return ServerResponse.createBySuccessData(categoryList);
    }

    /**
     * 递归查询本节点的id及孩子节点的id
     *
     * @param categoryId
     * @return
     */
    public ServerResponse<List<Integer>> selectCategoryAndChildrenById(Integer categoryId) {
        //初始化递归算法中的categorySet
        Set<Category> categorySet = Sets.newHashSet();
        findChildCategory(categorySet, categoryId);

        List<Integer> categoryIdList = new ArrayList();

        if (categoryId != null) {
            for (Category categoryItem : categorySet) {
                categoryIdList.add(categoryItem.getId());
            }
        }
        return ServerResponse.createBySuccessData(categoryIdList);
    }


    /**
     * 使用Set集合时要重写equal和hashcode方法，保证方法里边的判断因子（比较id的hash值）
     * 这样可以避免很多想不到的问题
     */
    //递归算法，算出子节点(就是自己调用自己)
    private Set<Category> findChildCategory(Set<Category> categorySet, Integer categoryId) {
        Category category = categoryMapper.selectByPrimaryKey(categoryId);
        if (category != null) {
            /*
            1.把第一次获得的对象A存入set集中
            2.如果A对象还有子节点，则把子节点所对应的对象B也存入set集中
            3.如果B对象还有子节点，则把子节点所对应的对象C也存入set集中
             */
            categorySet.add(category);
        }
        //查找子节点，递归算法一定要有一个退出条件 TODO 退出条件是集合遍历完毕，为空值
        List<Category> categoryList = categoryMapper.selectCategoryChildrenByParentId(categoryId);
        //mybatis 返回的集合，如果没有查到，不会是一个null对象，不用进行空判断
        /*
        4.如果C对象没有子节点，则集合为空，此时该递归算法退出
         */
        for (Category categoryItem : categoryList
                ) {
            findChildCategory(categorySet, categoryItem.getId());
        }
        return categorySet;
    }


}
